let express = require('express');
let app = express();
let fs = require("fs");
const httpsOption = {
    key : fs.readFileSync(__dirname+"/ssl/2_www.joyben.xyz.key"),
    cert: fs.readFileSync(__dirname+"/ssl/1_www.joyben.xyz_bundle.crt")
}
let https = require("https").createServer(httpsOption,app);
let io = require('socket.io')(https);
let PORT = 8089;
let users={},user_cnt=0;
let isInP2P={};
let video_room ='video_multi',text_room='text_chatting';
let video_users={};//记录加入视频聊天的id（key），name（value）
//转换http 请求为https

app.use(express.static('public'));
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/chatroom.html');
});
app.get('/test', (req, res) => {
    res.sendFile(__dirname + '/chatroom.html');
});

io.on('connection', (socket) => {
    socket.on('set nickname',function (user_name){
        users[socket.id]=user_name;
        user_cnt++;
        socket.join(text_room);//加入聊天室
        socket.emit('flash list',{list:users,num:user_cnt,room:text_room});
        socket.broadcast.emit('news', {what:"new",id:socket.id,name:user_name,num:user_cnt});
        console.log('新加入用户：'+user_name+socket.id+',当前在线人数：'+user_cnt);
    });
    socket.on('webrtc',function (data) {//服务器转发
        if(data.sdp&&data.sdp.type=='offer') console.log('视频请求：'+users[socket.id]+'---->'+users[data.id]);
        let rec=data.id;
        data.id=socket.id;
        socket.to(rec).emit('webrtc',data);
    });
    socket.on('chat_p2p',function (msgs) {
        //console.log('chat_p2p: '+msgs.what+',from:'+users[socket.id]+'to:'+users[msgs.id]+'val='+msgs.val);
        switch (msgs.what) {
            case "reply":
                // console.log('a reply from:'+users[socket.id]+'to:'+users[msgs.id]);
                if(msgs.val=='yes'){//socket.id同意
                    let room=msgs.id;//将对方id作为room，进入对方room
                    socket.join(room);//加入房间
                    socket.to(room).emit('chat_p2p', {what:'reply',id:socket.id,val:msgs.val});
                    //console.log('将'+room+'作为房间');
                    io.to(room).emit('chat_p2p',{what:'set_room',id2:socket.id,id:msgs.id,val:room});//将房间号告知用户
                }else if(msgs.val=='no'){//socket.id拒绝，告诉发送请求者
                    let sid=msgs.id;
                    msgs.id=socket.id;
                    socket.to(sid).emit('chat_p2p',msgs);
                }
                break;
            case "request"://如果对方已经在私聊，辣么就不建立p2p。
                // console.log('a request from:'+users[socket.id]+'to:'+users[msgs.id]);
                if(isInP2P[msgs.id]) socket.emit('chat_p2p', {what:'reply',id:msgs.id,val:'false'});
                else io.to(msgs.id).emit('chat_p2p',{what: 'request',id:socket.id});
                break;
            case "set_room":
                socket.leave(text_room);//退出群聊,这样解决用id找不了socket的玄学问题
                isInP2P[socket.id]=msgs.val;//将自己设置为私聊模式
                break;
            case "leave_out"://val有值就不再转发
                if(!msgs.val){
                    io.to(isInP2P[socket.id]).emit('chat_p2p',{what:'leave_out',val:text_room})
                    //console.log('转发out！')
                    break;
                }
                socket.leave(isInP2P[socket.id]);//不退出自己的room
                socket.join(socket.id);//加回自己
                //console.log('退出');

                socket.join(text_room);
                //console.log('删除记录！');
                delete isInP2P[socket.id];//记录的话两个都退！
                break;
            case "video":
                msgs.id=socket.id;
                socket.to(msgs.room).emit('chat_p2p',msgs);
                break;
            default:break;
        }
    });
    socket.on('msg_to',function (msgs) {
        if(msgs.type=='img')socket.to(msgs.room).emit('msg',{type:'img',data:msgs.data,id:socket.id,name:users[socket.id]});
        else socket.to(msgs.room).emit('msg', {type:'text',msg:msgs.data,id:socket.id,name:users[socket.id]});
    });
    // socket.on('msg_video',function (data) {
    //     socket.broadcast.to(video_room).emit('msg_video',{data:data,id:socket.id});
    // });
    socket.on('video_multi',function (data) {
        if(data.isNew){//新增视频连接
            console.log(users[socket.id]+"加入视频聊天！");
            socket.join(video_room);
            //告诉所有人有新人来
            socket.to(video_room).emit('video_multi', {isNew:true,id:socket.id});
            video_users[socket.id]=users[socket.id];//记录新加入的
            // 发送当前已经进入视频的列表,包括自己
            socket.emit('video_multi',{list:video_users,room:video_room});
            // socket.to(video_room).emit('newVideoDo',{isNew:true,id:socket.id,name:users[socket.id]})
        }else{//退出
            console.log(users[socket.id]+"退出视频聊天！")
            socket.to(video_room).emit('video_multi', {id:socket.id,isQuit: true});
            socket.leave(video_room);//退出聊天
            delete video_users[socket.id];//删除存储
        }
    });
    socket.on('disconnect',function () {
        //退出视频聊天
        socket.broadcast.to(video_room).emit('newVideoDo',{isNew:false,id:socket.id,name:users[socket.id]})
        //退出群聊
        socket.broadcast.emit('news', {what:"dis",id:socket.id,num:--user_cnt});
        if(isInP2P[socket.id]){
            io.to(isInP2P[socket.id]).emit('chat_p2p',{what:'leave_out',val:text_room});
            delete isInP2P[socket.id];
        }
        // console.log(users[socket.id]+' 退出群聊！'+',当前在线人数：'+user_cnt);

        delete users[socket.id];//删除存储
        delete video_users[socket.id];//删除存储
    });
});

https.listen(PORT, () => {
    console.log('listening on  https://127.0.0.1:'+PORT);
});